<?php
namespace app\index\controller;

use app\common\model\Article;
use app\common\model\Software;
use bigDream\thinkJump\Jump;
use think\facade\Request;
use think\facade\Validate;

class Search
{
    public function index()
    {
        return redirect(url('Search/software', ['keywords' => Request::param('keywords', '')]));
    }

    /**
     * 软件搜索
     * @return \think\response\View
     */
    public function software()
    {
        $data = Request::only(['keywords']);
        $validate = Validate::rule([
            'keywords|关键字' => ['require', 'length' => '2,18'],
        ]);
        if (!$validate->check($data)) {
            Jump::error($validate->getError());
        }

        $softwareCount = Software::where('name|remark', 'like', '%' . $data['keywords'] . '%')->count();
        $articleCount = Article::where('title|content', 'like', '%' . $data['keywords'] . '%')->where('status', 1)->count();

        $result = Software::with(['category'])
            ->where('name|remark', 'like', '%' . $data['keywords'] . '%')
            ->paginate(['query' => Request::except(['page'])], $softwareCount)
            ->each(function($item) use ($data) {
                $item->name = preg_replace('@(' . $data['keywords'] . ')@i', '<mark>\\1</mark>', $item->name);
                $item->remark = preg_replace('@(' . $data['keywords'] . ')@i', '<mark>\\1</mark>', $item->remark);
            });

        return view('', [
            'data'          => $data,
            'result'        => $result,
            'softwareCount' => $softwareCount,
            'articleCount'  => $articleCount,
        ]);
    }

    /**
     * 文章搜索
     * @return \think\response\View
     */
    public function article()
    {
        $data = Request::only(['keywords']);
        $validate = Validate::rule([
            'keywords|关键字' => ['require', 'length' => '2,18'],
        ]);
        if (!$validate->check($data)) {
            Jump::error($validate->getError());
        }

        $softwareCount = Software::where('name|remark', 'like', '%' . $data['keywords'] . '%')->count();
        $articleCount = Article::where('title|content', 'like', '%' . $data['keywords'] . '%')->where('status', 1)->count();

        $result = Article::with(['category'])
            ->where('title|content', 'like', '%' . $data['keywords'] . '%')
            ->paginate(['query' => Request::except(['page'])], $articleCount)
            ->each(function($item) use ($data) {
                $item->title = str_ireplace($data['keywords'], '<mark>' . $data['keywords'] . '</mark>', $item->title);
            });

        return view('', [
            'data'          => $data,
            'result'        => $result,
            'softwareCount' => $softwareCount,
            'articleCount'  => $articleCount,
        ]);
    }
}